﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using POP.Pop3;
using POP.Mime;
using POP.Mime.Decode;

namespace EmailClient
{
    class GetBodyEmail
    {
        string[] GetBodyEmailFromPop3Client(string pop3Host, int pop3Port, string account, string password, string path)
        {
            string[] BodyEmails = new string[1000];
            Pop3Client pop3Client = new Pop3Client();
            pop3Client.Connect(pop3Host, pop3Port, true);
            pop3Client.Authenticate(account, password);
            int messageNumber = pop3Client.GetMessageCount();
            int i = 0;
            while (!File.Exists(path + @"\" + pop3Client.GetMessage(messageNumber).Headers.MessageId + @".eml"))
            {
                FileStream file = new FileStream(path + @"\" + pop3Client.GetMessage(messageNumber).Headers.MessageId + @".eml", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                POP.Mime.Message message = pop3Client.GetMessage(messageNumber);
                MessagePart messagePart = message.FindFirstHtmlVersion();
                if (messagePart != null)
                    BodyEmails[i] = messagePart.GetBodyAsText();
                else
                {
                    messagePart = message.FindFirstPlainTextVersion();
                    if (messagePart != null)
                        BodyEmails[i] = messagePart.GetBodyAsText();
                    else
                        BodyEmails[i] = null;
                }
                i++;
                messageNumber--;
                if (messageNumber < 1)
                    break;
            }
            return BodyEmails;
        }

        string[] GetBodyEmailFromLocal(string path) 
        {
            string[] BodyEmails = new string[1000];
            string[] filePaths = Directory.GetFiles(path);
            int i = 0;
            if (filePaths != null)
            {
                foreach (string filePath in filePaths)
                {
                    FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    Message message = Message.Load(file);
                    file.Close();
                    MessagePart messagePart = message.FindFirstHtmlVersion();
                    if (messagePart != null)
                        BodyEmails[i] = messagePart.GetBodyAsText();
                    else
                    {
                        messagePart = message.FindFirstPlainTextVersion();
                        if (messagePart != null)
                            BodyEmails[i] = messagePart.GetBodyAsText();
                        else
                            BodyEmails[i] = null;
                    }
                    i++;
                }
            }
            return BodyEmails;
        }
    }
}

